package com.lhh.jiu.service.serviceImpl;

import com.lhh.jiu.constant.Constant;
import com.lhh.jiu.data.Result;
import com.lhh.jiu.service.FileService;
import com.lhh.jiu.util.FunctionUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Override
    public Result upload(MultipartFile file) {
        //判断文件是否为空
        if (file.isEmpty()){
            return new Result(403,"","文件为空");
        }
        //判断文件的大小
        boolean status = FunctionUtil.checkFileSize(file.getSize(),20000,"M");
        if (!status){
            return new Result(403,"","文件大小超出了限制");
        }

        //获取文件名
        String fileName = file.getOriginalFilename();
        System.out.println("用户名：" + fileName);
        //获取图片的后缀，如图片的png,jpg等
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        System.out.println("上传文件的后缀："+suffixName);
        String checkStr = ".png,.jpg,.jpeg";
        boolean strStatus = checkStr.contains(suffixName);
        if (!strStatus){
            return new Result(403,"","上传文件的后缀不一致");
        }

        //文件上传后的路径
        fileName = UUID.randomUUID() + suffixName;
        System.out.println("转换后的图片名称："+fileName);

        Date date = new Date();
        String filePath = Constant.File_PATH + new SimpleDateFormat("yyyy-MM-dd").format(date);
        //如果不存在,创建文件夹
        File f = new File(filePath);
        if(!f.exists()){
            f.mkdirs();
        }
        System.out.println("上传路径："+filePath);

        File dest = new File(filePath+ "/" + fileName);
        try{
            file.transferTo(dest);//MultipartFile 对象的transferTo方法，用于文件保存（效率和操作比原先用FileOutStream方便和高效）
            return new Result(200,fileName,"上传成功");
        }catch (IllegalStateException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }

        return new Result(403,"","上传失败");
    }
}
